import sys
import io
import os


# 设置标准输出编码为UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

class ReadRegisterCreator:
    def __init__(self, name):
        self._name = name
        self.name = f"{name}_read"
        self.source_file = f"{ self.name}.c"
        self.include_file = f"{ self.name}.h"
        self.registers = []  # 用于存储寄存器名称和地址
        self.end_guard = f"\n#endif // __{self.name.upper()}_H__\n"
        self.format_init()
        self.function_begin = f"unsigned int {self.name}_data(void) {{\n    unsigned int data = 0;\n"
        self.function_end = f"    return data;\n\n}} // {self.name} end\n"
    def include_file_init(self):
        # 写入头文件格式
        define_guard = f"#ifndef __{self.name.upper()}_H__\n#define __{self.name.upper()}_H__\n\n"
        # extern_struct_def = f"extern struct {self._name}_register {self._name};\n"

        function_name = f"unsigned int {self.name}_data(void);"
        with open(self.include_file, 'w', encoding='utf-8') as file:
            file.write(define_guard)
            # file.write(extern_struct_def)
            file.write(function_name)
            file.write(self.end_guard)

    def source_file_init(self):
        # 写入源文件格式
        # struct_def = f"struct {self._name}_register {self._name};\n"
        free_function_prefix = f"/**************{self._name}free write begin**************/\n"
        test_write = " \n"
        free_function_suffix = f"/**************{self._name}free write end**************/\n"
        # struct_init = f"{self._name} = init_{self._name}_register();\n"
        try:
            with open(self.source_file, 'r+', encoding='utf-8') as file:
                test = file.read()
                # 找到free_function_prefix的位置并删除它前面的所有内容
                prefix_index = test.find(free_function_prefix)
                if prefix_index != -1:
                    test = test[prefix_index + len(free_function_prefix):]

                # 找到free_function_suffix的位置并删除它后面的所有内容
                suffix_index = test.find(free_function_suffix)
                if suffix_index != -1:
                    test = test[:suffix_index]
                # 查找函数的开始部分
                test_write = test
        except FileNotFoundError:
            pass
        with open(self.source_file, 'w+', encoding='utf-8') as file:
            file.write(f"#include \"{self.include_file}\"\n#include \"{self._name}_register.h\"\n#include \"{self._name}_config.h\"\n")
            # file.write(struct_def)
            file.write(free_function_prefix)
            file.write(test_write)
            file.write(free_function_suffix)


    def format_init(self):
        #第一次初始化
        self.include_file_init()
        self.source_file_init()
    def read_config(self, register_name, register_data):
         # 写入寄存器配置
        write_data = f"    {self._name}_read({self._name}.{register_name});\n    data |= {self._name}.{register_name}[1];\n    data = data {register_data};\n\n"
        # 检查文件是否存在，如果不存在，则创建文件并写入函数的开始部分
        if not os.path.exists(self.source_file):
            with open(self.source_file, 'w', encoding='utf-8') as file:
                file.write(self.function_begin)
                file.write(self.function_end)
        
        # 读取现有文件内容
        with open(self.source_file, 'r+', encoding='utf-8') as file:
            content = file.read()
            # 查找函数的开始部分
            begin_index = content.find(self.function_begin)
            if begin_index != -1:
                # 移除函数的开始部分和结束部分
                content = content[:begin_index] + content[begin_index:].split(self.function_end, 1)[0]
            else:
                # 如果函数开始部分不存在，则添加它
                content += self.function_begin

            # 将新的配置行添加到函数体内
            content += write_data

            # 将函数的结束部分添加回文件
            content += self.function_end
        
        # 将修改后的内容写回文件
        with open(self.source_file, 'w', encoding='utf-8') as file:
            file.write(content)


if __name__ == '__main__':
    creator = ReadRegisterCreator("test")
    creator.read_config("A", "<<24")
    creator.read_config("B", ">>16")
    creator.read_config("C", "")